<template>
  <div class="nursing-page">
    <!-- 1. 楼层切换（标签式） -->
    <div class="floor-tabs">
      <label 
        v-for="floor in floorTabs" 
        :key="floor" 
        class="floor-tab" 
        :class="{ active: activeFloor === floor }"
        @click="activeFloor = floor"
      >
        {{ floor }}
      </label>
    </div>

    <!-- 2. 房间列表（根据楼层切换） -->
    <div 
      v-for="(roomGroup, index) in currentRooms" 
      :key="`room-group-${index}`" 
      class="room-card"
    >
      <!-- 房间头部：房间号 -->
      <div class="room-header">
        <span>房间号：{{ roomGroup.roomNo }}</span>
        <el-button 
          type="primary" 
          size="mini"
          @click="openBatchCarerDialog(roomGroup)"
        >
          批量设置护理员
        </el-button>
      </div>

      <!-- 床位列表 -->
      <div class="bed-list">
        <div 
          v-for="(bed, bedIndex) in roomGroup.beds" 
          :key="`bed-${bed.bedNo}`" 
          class="bed-item"
        >
          <div class="bed-info">
            <p>床位号：{{ bed.bedNo }}</p>
            <p>老人姓名：{{ bed.elderName }}</p>
            <div class="carer-wrap">
              <span class="carer-label">护理员姓名：</span>
              <div class="carer-list">
                <!-- 护理员标签 -->
                <el-button 
                  v-for="(carer, cIndex) in bed.carers" 
                  :key="`carer-${cIndex}`" 
                  type="text" 
                  size="mini"
                >
                  {{ carer }}
                </el-button>
                <span v-if="bed.carers.length === 0" class="no-carer">当前床位没有安排护理员</span>
              </div>
            </div>
            <el-button 
              type="text" 
              size="mini" 
              class="set-btn"
              @click="openCarerDialog(roomGroup, bed)"
            >
              设置护理员
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 护理员设置弹窗 -->
    <el-dialog
      v-model="carerDialogVisible"
      title="设置护理员"
      width="500px"
    >
      <div class="carer-dialog-content">
        <div class="dialog-description">
          <span v-if="isBatchMode">
            为房间 {{ currentRoom?.roomNo }} 批量设置护理员（最多选择4人）
          </span>
          <span v-else>
            为 {{ currentRoom?.roomNo }} - {{ currentBed?.bedNo }} 床位设置护理员（最多选择4人）
          </span>
        </div>
        
        <el-checkbox-group 
          v-model="selectedCarers"
          class="carer-checkbox-group"
        >
          <!-- 【核心修改】添加动态disabled：选中数≥4且当前护理员未被选中时，置灰不可点击 -->
          <el-checkbox 
            v-for="carer in allCarers" 
            :key="carer.id" 
            :label="carer.name"
            class="carer-checkbox"
            :disabled="selectedCarers.length >= 4 && !selectedCarers.includes(carer.name)"
          >
            {{ carer.name }}
          </el-checkbox>
        </el-checkbox-group>
        
        <div class="selected-carers">
          <p class="selected-title">已选护理员：</p>
          <div class="selected-tags">
            <el-tag 
              v-for="(carer, index) in selectedCarers" 
              :key="index"
              closable
              @close="removeCarer(carer)"
            >
              {{ carer }}
            </el-tag>
            <span v-if="selectedCarers.length === 0" class="no-selected">暂无选择</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="carerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCarerSetting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

// 1. 响应式变量（存储后端原始数据分组结果）
const floorData = ref([]) // 格式：[{name: '1楼', rooms: [{roomNo: 'R001', beds: []}]}]
const floorTabs = ref([]) // 动态提取后端楼层名（如['1楼', '2楼']）
const activeFloor = ref('') // 当前激活的楼层

// 2. 护理员相关变量
const allCarers = ref([]) // 所有护理员列表
const selectedCarers = ref([]) // 当前选中的护理员
const carerDialogVisible = ref(false) // 弹窗显示状态
const isBatchMode = ref(false) // 是否批量设置模式
const currentRoom = ref(null) // 当前操作的房间
const currentBed = ref(null) // 当前操作的床位

// 3. 根据当前楼层筛选房间
const currentRooms = computed(() => {
  const targetFloor = floorData.value.find(floor => floor.name === activeFloor.value)
  return targetFloor ? targetFloor.rooms : []
})

// 4. 处理后端数据
const processBackendData = (rawData) => {
  const floorMap = {}

  rawData.forEach(item => {
    const { floorName, roomNo, bedNo, elderName, carersStr } = item

    if (!floorMap[floorName]) {
      floorMap[floorName] = {
        name: floorName,
        rooms: []
      }
    }

    let targetRoom = floorMap[floorName].rooms.find(room => room.roomNo === roomNo)
    if (!targetRoom) {
      targetRoom = {
        roomNo: roomNo,
        beds: []
      }
      floorMap[floorName].rooms.push(targetRoom)
    }

    const carers = carersStr ? carersStr.split(',') : []

    targetRoom.beds.push({
      bedNo: bedNo,
      elderName: elderName,
      carers: carers
    })
  })

  return Object.values(floorMap)
}

// 5. 请求数据
const getFloorData = () => {
  request({
    url: '/system/job/list',
    method: 'get'
  }).then(res => {
    if (res.code === 200) {
      console.log('原始数据:', res.data);
      const processedData = processBackendData(res.data);
      console.log('处理后的数据:', processedData);
      floorData.value = processedData;
      // 1. 先获取新的楼层列表
      const newFloorTabs = processedData.map(floor => floor.name);
      floorTabs.value = newFloorTabs;

      // 2. 关键：保持当前activeFloor（如果它仍在新楼层列表中）
      if (newFloorTabs.length > 0) {
        // 如果当前activeFloor在新楼层列表中，就不变；否则用第一个楼层
        if (!newFloorTabs.includes(activeFloor.value)) {
          activeFloor.value = newFloorTabs[0];  // 仅在当前楼层不存在时才重置
        }
        // 否则保持activeFloor不变（用户当前选中的楼层）
      }
    }
  }).catch(error => {
    console.error('请求失败：', error);
  });
}

// 6. 获取护理员列表（实际项目中应从后端获取）
const getCarersList = () => {
  // 模拟后端数据，实际项目中替换为真实接口
  request({
    url: '/system/job/carerList',
    method: 'get'
  }).then(res => {
    if (res.code === 200) {
      allCarers.value = res.data
    }
  }).catch(() => {
    // 模拟数据
    allCarers.value = [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' },
      { id: 3, name: '王五' },
      { id: 4, name: '赵六' },
      { id: 5, name: '孙七' },
      { id: 6, name: '周八' } // 新增1个护理员用于测试限制效果
    ]
  })
}

// 7. 打开护理员设置弹窗（单个床位）
const openCarerDialog = (room, bed) => {
  isBatchMode.value = false
  currentRoom.value = room
  currentBed.value = bed
  // 回显已有护理员（若原有数量≥4，仍正常回显，不影响取消操作）
  selectedCarers.value = [...bed.carers]
  carerDialogVisible.value = true
}

// 8. 打开批量设置护理员弹窗
const openBatchCarerDialog = (room) => {
  isBatchMode.value = true
  currentRoom.value = room
  currentBed.value = null
  selectedCarers.value = []
  carerDialogVisible.value = true
}

// 9. 移除已选护理员
const removeCarer = (carerName) => {
  selectedCarers.value = selectedCarers.value.filter(name => name !== carerName)
  // 取消选中后，禁用的复选框会自动恢复可用（因disabled条件动态变化）
}

// 10. 确认设置护理员
const confirmCarerSetting = () => {
  if (isBatchMode.value) {
    currentRoom.value.beds.forEach(bed => {
      bed.carers = [...selectedCarers.value]
    })
  } else {
    currentBed.value.carers = [...selectedCarers.value]
  }
  
  saveCarerSetting()
  carerDialogVisible.value = false
}

// 11. 保存护理员设置到后端
const saveCarerSetting = () => {
  const data = isBatchMode.value 
    ? {
        roomNo: currentRoom.value.roomNo,
        carersStr: selectedCarers.value.join(','),
        isBatch: true
      }
    : {
        roomNo: currentRoom.value.roomNo,
        bedNo: currentBed.value.bedNo,
        carersStr: selectedCarers.value.join(','),
        isBatch: false
      }
  
  console.log('保存护理员设置:', data)
  
  request({
    url: '/system/job/carerSet',
    method: 'post',
    data
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('设置成功')
      getFloorData()  // 刷新数据
    }else{
      ElMessage.error('设置失败')
    }
  })
  
}

// 12. 页面挂载时请求数据
onMounted(() => {
  getFloorData()
  getCarersList()
})
</script>

<style scoped>
/* 原有样式保持不变 */
.nursing-page {
  padding: 24px;
  background: #F5F7FA;
}

.floor-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}
.floor-tab {
  padding: 6px 16px;
  border: 1px solid #409EFF;
  border-radius: 20px;
  color: #409EFF;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}
.floor-tab.active {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
}

.room-card {
  background: #fff;
  border: 1px solid #E6E6E6;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.room-header span {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}
.room-header .el-button {
  padding: 4px 12px;
  font-size: 12px;
}

.bed-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.bed-item {
  flex: 1;
  min-width: 260px;
  background: #F5F7FA;
  border: 1px solid #E6E6E6;
  border-radius: 6px;
  padding: 12px;
}
.bed-info {
  display: flex;
  flex-direction: column;
}
.bed-info p {
  margin: 6px 0;
  font-size: 14px;
  color: #333;
}

.carer-wrap {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-top: 4px;
  margin-bottom: 8px;
}
.carer-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
}
.carer-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.carer-list .el-button {
  padding: 4px 8px;
  font-size: 12px;
  color: #409EFF;
  border: 1px solid #409EFF;
  border-radius: 4px;
  background: #fff;
}
.no-carer {
  font-size: 12px;
  color: #999;
  margin-left: 4px;
}

.set-btn {
  align-self: flex-end;
  margin-top: 12px;
  font-size: 12px;
  color: #409EFF;
  padding: 0;
}

/* 新增弹窗样式 */
.carer-dialog-content {
  padding: 10px 0;
}

.dialog-description {
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  color: #666;
}

.carer-checkbox-group {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.carer-checkbox {
  width: 50%;
  margin-bottom: 8px;
}

.selected-carers {
  margin-top: 16px;
}

.selected-title {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.no-selected {
  color: #999;
  font-size: 12px;
}
</style>